import gio
import gtk
import threading
from mmxfer import mediatype
from mmxfer import store
import traceback
import tempfile
import time
import os

class WorkerThread_Copy(threading.Thread):
	def __init__(self,lstore):
		threading.Thread.__init__(self)
		self.lstore=lstore
		self.cancel_object=gio.Cancellable()
	def run(self):
		while not self.lstore.quit_event.is_set():
			gtk.gdk.threads_enter()
			task_row=None
			for row in self.lstore:
				if row[store.column("waiting")] \
						and row[store.column("type")]==mediatype.MT_REMOTE:
					task_row=row
					break
			if task_row is None:
				gtk.gdk.threads_leave()
				self.lstore.quit_event.wait(0.1)
				continue
			task_row[store.column("status")]=mediatype.get_description(mediatype.MT_REMOTE,False)
			task_row[store.column("waiting")]=False
			uri=task_row[store.column("uri")]
			gtk.gdk.threads_leave()
			result=False
			dest_name=""
			try:
				src=gio.File(uri)
				n,ext=suffix=os.path.splitext(src.get_path())
				dest_name=tempfile.NamedTemporaryFile(suffix=ext,delete=False)
				dest=gio.File(dest_name.name)
				task_row[store.column("tmp")].append(dest.get_path())
				dest_name.close()
				self.cancel_object.reset()
				src.copy(dest,cancellable=self.cancel_object,
						progress_callback=self.progress_callback,user_data=task_row,flags=gio.FILE_COPY_OVERWRITE)
				result=True
			except gio.Error,e:
				if not self.cancel_object.is_cancelled():
					traceback.print_exc()
			except:
				traceback.print_exc()
			if self.cancel_object.is_cancelled():
				task_row[store.column("tmp")]=task_row[store.column("tmp")][:-1]
				self.cancel_object.reset()
			gtk.gdk.threads_enter()
			if result:
				type=mediatype.find_type(dest.get_path())
				if type != mediatype.MT_UNKNOWN and mediatype != mediatype.MT_REMOTE:
					task_row[store.column("uri")]=dest.get_path()
					task_row[store.column("type")]=type
					task_row[store.column("status")]=mediatype.get_description(type,True)
					task_row[store.column("progress")]=0.0
				else:
					result=False
			if not result:
				dest.delete()
				task_row[store.column("type")]=mediatype.MT_UNKNOWN
				task_row[store.column("status")]=mediatype.get_description(mediatype.MT_UNKNOWN,False)
				task_row[store.column("progress")]=0.0
			task_row[store.column("waiting")]=True
			gtk.gdk.threads_leave()

				
	def progress_callback(self,current,max,row):
		try:
			gtk.gdk.threads_enter()
			row[store.column("progress")]=float(current)/float(max)*100.0
		finally:
			gtk.gdk.threads_leave()
		if self.lstore.quit_event.is_set():
			self.cancel_object.cancel()
			

